import { createSlice } from '@reduxjs/toolkit';

// 默认讨论数据
const defaultPosts = [
  {
    id: 1,
    title: 'React Router v6 的使用心得',
    content: '最近在学习 React Router v6，发现相比 v5 有很多改进，特别是在路由配置和 Hooks 的使用上。分享一下我的学习心得...',
    author: {
      id: 1,
      name: '张三',
      avatar: 'https://via.placeholder.com/40'
    },
    courseId: 1,
    category: 'share',
    createTime: '2024-03-15 14:30',
    likeCount: 25,
    commentCount: 8,
    comments: [
      {
        id: 1,
        content: '感谢分享，对我很有帮助！',
        author: {
          id: 2,
          name: '李四',
          avatar: 'https://via.placeholder.com/40'
        },
        createTime: '2024-03-15 15:00',
        likeCount: 5
      },
      {
        id: 2,
        content: '能详细说说 useNavigate 的使用场景吗？',
        author: {
          id: 3,
          name: '王五',
          avatar: 'https://via.placeholder.com/40'
        },
        createTime: '2024-03-15 15:30',
        likeCount: 3
      }
    ]
  },
  {
    id: 2,
    title: '求助：Redux 状态管理问题',
    content: '在使用 Redux 管理复杂状态时遇到了一些问题，特别是在处理异步操作时，不知道该如何正确使用 thunk middleware...',
    author: {
      id: 4,
      name: '赵六',
      avatar: 'https://via.placeholder.com/40'
    },
    courseId: 1,
    category: 'question',
    createTime: '2024-03-15 16:00',
    likeCount: 10,
    commentCount: 5,
    comments: [
      {
        id: 3,
        content: '建议看看 Redux Toolkit，它简化了很多 Redux 的使用方式',
        author: {
          id: 5,
          name: '王老师',
          avatar: 'https://via.placeholder.com/40'
        },
        createTime: '2024-03-15 16:30',
        likeCount: 8
      }
    ]
  },
  {
    id: 3,
    title: '分享一些实用的 React 性能优化技巧',
    content: '整理了一些在实际项目中常用的 React 性能优化方法，包括 React.memo、useMemo、useCallback 的使用场景...',
    author: {
      id: 6,
      name: '李老师',
      avatar: 'https://via.placeholder.com/40'
    },
    courseId: 2,
    category: 'share',
    createTime: '2024-03-15 17:00',
    likeCount: 45,
    commentCount: 12,
    comments: [
      {
        id: 4,
        content: '这些优化技巧太实用了！',
        author: {
          id: 7,
          name: '小明',
          avatar: 'https://via.placeholder.com/40'
        },
        createTime: '2024-03-15 17:30',
        likeCount: 6
      }
    ]
  }
];

// 修改 loadInitialPosts 函数，添加错误处理和本地存储回退
const loadInitialPosts = () => {
  try {
    // 尝试从本地存储加载数据
    const savedPosts = localStorage.getItem('discussionPosts');
    if (savedPosts) {
      return JSON.parse(savedPosts);
    }
    // 如果本地存储没有数据，使用默认数据并保存到本地存储
    localStorage.setItem('discussionPosts', JSON.stringify(defaultPosts));
    return defaultPosts;
  } catch (error) {
    console.error('Error loading posts from localStorage:', error);
    return defaultPosts;
  }
};

// 保存数据到 localStorage
const savePostsToStorage = (posts) => {
  try {
    localStorage.setItem('discussionPosts', JSON.stringify(posts));
  } catch (error) {
    console.error('Error saving posts to localStorage:', error);
  }
};

const discussionSlice = createSlice({
  name: 'discussion',
  initialState: {
    posts: loadInitialPosts(),
    loading: false,
    error: null
  },
  reducers: {
    setPosts: (state, action) => {
      state.posts = action.payload;
      savePostsToStorage(action.payload);
    },
    addPost: (state, action) => {
      state.posts.unshift(action.payload);
      savePostsToStorage(state.posts);
    },
    updatePost: (state, action) => {
      const { postId, updates } = action.payload;
      const post = state.posts.find(p => p.id === postId);
      if (post) {
        Object.assign(post, updates);
        savePostsToStorage(state.posts);
      }
    },
    deletePost: (state, action) => {
      state.posts = state.posts.filter(post => post.id !== action.payload);
      savePostsToStorage(state.posts);
    },
    addComment: (state, action) => {
      const { postId, comment } = action.payload;
      const post = state.posts.find(p => p.id === postId);
      if (post) {
        post.comments.push(comment);
        post.commentCount += 1;
        savePostsToStorage(state.posts);
      }
    },
    deleteComment: (state, action) => {
      const { postId, commentId } = action.payload;
      const post = state.posts.find(p => p.id === postId);
      if (post) {
        post.comments = post.comments.filter(comment => comment.id !== commentId);
        post.commentCount -= 1;
        savePostsToStorage(state.posts);
      }
    },
    setLoading: (state, action) => {
      state.loading = action.payload;
    },
    setError: (state, action) => {
      state.error = action.payload;
    }
  }
});

export const {
  setPosts,
  addPost,
  updatePost,
  deletePost,
  addComment,
  deleteComment,
  setLoading,
  setError
} = discussionSlice.actions;

export default discussionSlice.reducer; 